package filter;

import redis.clients.jedis.Jedis;
import utils.Redis;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter("*.html")
public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;

        String requestURI = req.getRequestURI();
        /**
         * 此情况是用户直接访问注册的第二步骤
         * 如果没有第一步骤的参数 将拦截 并且转到注册第一步骤
         */

        Jedis jedis = new Jedis();
        //获取用户客户端标识
        String redisKey = Redis.getRedisKey(req);
        String s = jedis.get(redisKey);

        //如果是登录页面或注册页面直接放行
//        if ("/LoveDown_war/login.html".equals(requestURI) || "/LoveDown_war/register.html".equals(requestURI)
//                || "/LoveDown_war/index.html".equals(requestURI)
//        ) {
        if (s != null || requestURI.endsWith("/") || requestURI.endsWith("login.html") || requestURI.endsWith("register.html") || requestURI.endsWith("index.html")
            || requestURI.endsWith("next_reg.html") || requestURI.endsWith("success.html")){

            filterChain.doFilter(req, resp);
        }else {
            //没有用户登录
            resp.sendRedirect("login.html");
        }
    }

    @Override
    public void destroy() {

    }
}
